﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTunesLib;

namespace com.netkow.KinecTunes.iTunes
{
    public class ItunesConnector
    {
        public iTunesApp itunesApp = null;
        public List<KinecTrack> allItunesTracks { get; set; }

        /// <summary>
        /// Constructor - Open iTunes.
        /// </summary>
        public ItunesConnector()
        {
            try
            {
                this.itunesApp = new iTunesLib.iTunesApp();
            }
            catch (Exception)
            {
                throw new Exception("Problem loading iTunes.");
            }
        }

        /// <summary>
        /// Parse the user's full iTunes library, extracting Track information.
        /// </summary>
        /// <returns>list of all iTunes audio tracks</returns>
        public List<KinecTrack> GetFullLibrary()
        {
            allItunesTracks = new List<KinecTrack>();

            var mainLibrary = this.itunesApp.LibraryPlaylist;

            // iTunes uses 1-based indexing
            for (int i = 1; i <= mainLibrary.Tracks.Count; i++)
            {
                IITTrack track = mainLibrary.Tracks[i];
                // Only add audio files
                if (track != null && track.KindAsString.Contains("audio"))
                {
                    KinecTrack kinecTrack = new KinecTrack
                    {
                        Index = i,
                        Artist = track.Artist,
                        Name = track.Name
                    };

                    allItunesTracks.Add(kinecTrack);
                }
            }

            return allItunesTracks;
        }

        /// <summary>
        /// Pick a random song from the selected Artist to play.
        /// </summary>
        /// <param name="artist">the artist</param>
        /// <returns>the library index of the selected song</returns>
        public int GetRandomSongFromArtist(string artist)
        {
            if (string.IsNullOrEmpty(artist)) throw new ArgumentNullException("Artist name cannot be null.");

            int result = -1;

            var allArtistSongIndices =  from t in allItunesTracks
                                        where t.Artist == artist
                                        select t.Index;

            Random random = new Random();
            result = random.Next(allArtistSongIndices.Min(), allArtistSongIndices.Max());

            return result;
        }

        /// <summary>
        /// Play the desired track based on the given index.
        /// </summary>
        /// <param name="index">the iTunes song index</param>
        /// <returns>the selected track to play</returns>
        public KinecTrack Play(int index)
        {
            if (index <= 0) throw new ArgumentNullException("Index must be greater than zero.");

            IITTrack iittrack = this.itunesApp.LibraryPlaylist.Tracks[index];
            return this.Play(iittrack);
        }

        /// <summary>
        /// Play the desired track based on the given track name.
        /// Note: If two or more tracks share the same name, iTunes will choose the song with the smallest 
        /// index.
        /// </summary>
        /// <param name="trackName">the name of the track to play</param>
        /// <returns>the selected track to play</returns>
        public KinecTrack Play(string trackName)
        {
            if (string.IsNullOrEmpty(trackName)) throw new ArgumentNullException("Trackname cannot be null.");

            IITTrack iittrack = this.itunesApp.LibraryPlaylist.Tracks.get_ItemByName(trackName);
            return this.Play(iittrack);
        }

        /// <summary>
        /// Play the given track.
        /// </summary>
        /// <param name="trackToPlay">the track to play</param>
        /// <returns>the selected track to play</returns>
        private KinecTrack Play(IITTrack trackToPlay)
        {
            KinecTrack result = null;

            if (trackToPlay != null)
            {
                result = new KinecTrack
                {
                    Artist = trackToPlay.Artist,
                    Album = trackToPlay.Album,
                    Name = trackToPlay.Name,
                    Index = trackToPlay.Index
                };

                trackToPlay.Play();
            }

            return result;
        }

        /// <summary>
        /// Resume a paused song's playback.
        /// </summary>
        public void Resume()
        {
            this.itunesApp.Play();
        }

        /// <summary>
        /// Pause the currently playing song.
        /// </summary>
        public void Pause()
        {
            this.itunesApp.Pause();
        }

        /// <summary>
        /// Stop playing the current song.
        /// </summary>
        public void Stop()
        {
            this.itunesApp.Stop();
        }
    }
}
